using System;
using Serpis;
using System.Data;
using System.Reflection;

namespace PArticulo
{
	
	public class ArticuloPersister
	{
		private IDbCommand dbCommand;
		
		public ArticuloPersister ()
		{
			
		}
		//**	Devuelve un Articulo con los parametros extraidos de la Base de Datos en función del Id que recibe
		public Articulo Load(long id)
		{
			dbCommand= AppDbConnection.Instance.DbConnection.CreateCommand();
			string commandText = "SELECT * FROM articulo WHERE id='"+id+"';";		
			dbCommand.CommandText = commandText;
			IDataReader dataReader = dbCommand.ExecuteReader();
			dataReader.Read();
			
			Articulo articulo= new Articulo();
			articulo.Id= (long)dataReader[0];
			articulo.Nombre= dataReader[1] is DBNull ? "" : (string)dataReader[1];
			articulo.Precio= dataReader[2] is DBNull ? 0 : (decimal)dataReader[2];
			articulo.Categoria= dataReader[3] is DBNull ? (long?)null : (long)dataReader[3];
			
			dataReader.Close();
			
			return articulo;			
		}
		public void Save(Articulo articulo)
		{
			dbCommand= AppDbConnection.Instance.DbConnection.CreateCommand();
			string commandText;
			
			IDbDataParameter dbParameter= dbCommand.CreateParameter();
			dbParameter.ParameterName= "nombre";
			dbParameter.Value= articulo.Nombre;
			dbCommand.Parameters.Add(dbParameter);
			
			dbParameter= dbCommand.CreateParameter();
			dbParameter.ParameterName= "precio";
			dbParameter.Value= articulo.Precio;
			dbCommand.Parameters.Add(dbParameter);
			
			dbParameter= dbCommand.CreateParameter();
			dbParameter.ParameterName= "categoria";
			dbParameter.Value= articulo.Categoria;
			dbCommand.Parameters.Add(dbParameter);
			
			if(articulo.Id == 0)
			{
				commandText= "INSERT INTO articulo (nombre,precio,categoria) VALUES (?nombre,?precio,?categoria);";
			}
			else
			{
				commandText="UPDATE articulo SET nombre=?nombre,precio=?precio,categoria=?categoria"+" WHERE id="+articulo.Id+";";
			}		
			dbCommand.CommandText= commandText;
			dbCommand.ExecuteNonQuery();
		}
		public void Delete(Articulo articulo) 
		{
			IDbCommand dbCommand= AppDbConnection.Instance.DbConnection.CreateCommand();
			string commandText= "DELETE FROM articulo WHERE id="+articulo.Id+";";
			dbCommand.CommandText= commandText;
			dbCommand.ExecuteNonQuery();
		}
	}
}
